package msrc

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func Test_livenessController_Ready(t *testing.T) {
	type fields struct {
		mainService MultiServiceInterface
	}
	type args struct {
		writer http.ResponseWriter
	}
	tests := []struct {
		name   string
		fields fields
		args   args
		want   bool
	}{
		{
			name: "Тестирование, когда контент не готов",
			fields: fields{
				mainService: &MultiServiceMock{
					IsAlive: false,
					IsRun:   false,
				},
			},
			args: args{
				writer: httptest.NewRecorder(),
			},
			want: false,
		},
		{
			name: "Тестирование, когда контент готов",
			fields: fields{
				mainService: &MultiServiceMock{
					IsAlive: false,
					IsRun:   true,
				},
			},
			args: args{
				writer: httptest.NewRecorder(),
			},
			want: true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			l := newLivenessService("39100", tt.fields.mainService)
			go func() {
				_ = l.Run()
			}()

			defer l.GracefulShutdown()

			time.Sleep(100 * time.Millisecond)

			res, err := http.Get("http://localhost:39100/ready")
			if nil != err {
				t.Fatalf(`/ready error=%v, want=nil`, err)
			}

			switch tt.want {
			case true:
				if res.StatusCode != http.StatusOK {
					t.Fatalf(`/ready status=%v, want=%v`, res.StatusCode, http.StatusOK)
				}
			case false:
				if res.StatusCode != http.StatusInternalServerError {
					t.Fatalf(`/ready status=%v, want=%v`, res.StatusCode, http.StatusInternalServerError)
				}
			}
		})
	}
}

func Test_livenessController_Alive(t *testing.T) {
	type fields struct {
		mainService MultiServiceInterface
	}
	type args struct {
		writer http.ResponseWriter
	}
	tests := []struct {
		name   string
		fields fields
		args   args
		want   bool
	}{
		{
			name: "Тестирование, когда контент не готов",
			fields: fields{
				mainService: &MultiServiceMock{
					IsAlive: false,
					IsRun:   false,
				},
			},
			args: args{
				writer: httptest.NewRecorder(),
			},
			want: false,
		},
		{
			name: "Тестирование, когда контент готов",
			fields: fields{
				mainService: &MultiServiceMock{
					IsAlive: true,
					IsRun:   false,
				},
			},
			args: args{
				writer: httptest.NewRecorder(),
			},
			want: true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			l := newLivenessService("39100", tt.fields.mainService)
			go func() {
				_ = l.Run()
			}()

			defer l.GracefulShutdown()

			time.Sleep(100 * time.Millisecond)

			res, err := http.Get("http://localhost:39100/alive")
			if nil != err {
				t.Fatalf(`/alive error=%v, want=nil`, err)
			}

			switch tt.want {
			case true:
				if res.StatusCode != http.StatusOK {
					t.Fatalf(`/alive status=%v, want=%v`, res.StatusCode, http.StatusOK)
				}
			case false:
				if res.StatusCode != http.StatusInternalServerError {
					t.Fatalf(`/alive status=%v, want=%v`, res.StatusCode, http.StatusInternalServerError)
				}
			}
		})
	}
}
